<?php
/**
 * 活动信息
 * http://baseAddress/api/activity/
 */

namespace App\Http\Controllers\Api\Activity;

use App\App\Services\CsvReaderService;
use App\App\Services\StorageService;
use App\App\Services\Web\ActivityService;
use App\Http\Controllers\Controller;
use App\Models\ActivityInfo\ActivityInfoService;
use App\Models\ActivityRecord\ActivityRecordService;
use App\Models\PrizeRecord\PrizeRecord;
use App\Models\PrizeRecord\PrizeRecordService;
use Illuminate\Http\Request;

class ActivityController extends Controller
{
    public function activity(Request $request, ActivityInfoService $activityService)
    {
        if ($request->isMethod('get')) {
            if ($request->request->get('activity_id')) {
                $activity = $activityService->getActivity($request->request->get('activity_id'));

                return $this->respondJson(['activity' => $activity]);
            } else {
                return $this->respondJson(['activity' => []], 300);
            }
        } elseif ($request->isMethod('post')) {
            if (!empty($request->request->all())) {
                $result = $activityService->createActivity($request->request->all());
                if ($result) {
                    return $this->respondJson(['result' => 'success']);
                }
            } else {
                return $this->respondJson(['result' => 'fail'], 300);
            }
        }
    }

    /**
     * 新增活动信息
     *
     * @param Request             $request
     * @param ActivityInfoService $activityService
     * @param PrizeRecordService  $prizeRecordService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request, ActivityInfoService $activityService, PrizeRecordService $prizeRecordService)
    {
        $requestData = $request->request->all();
        $activityInfo = [
            'name'   => $requestData['name'],
            'method' => $requestData['method'] ?: 0,
        ];
        $activityId = $activityService->createActivity($activityInfo);
        if ($activityId) {
            if (is_string($requestData['prize'])) {
                $requestData['prize'] = json_decode($requestData['prize'], true);
            }
            foreach ($requestData['prize'] as $requestDatum) {
                $prizeRecord[] = [
                    'activity_id' => $activityId,
                    'prize_id'    => $requestDatum['prize_id'],
                    'limit'       => $requestDatum['limit'],
                    'number'      => $requestDatum['number'],
                    'summary'     => $requestDatum['summary'],
                    'probability' => $requestDatum['probability'],
                    'operate'     => PrizeRecord::DELIVERY,
                    'created_at'  => date('Y-m-d H:i:s'),
                ];
                $activityService->updateActivityPrize($activityId, $requestDatum['prize_id']);
            }
            $prizeRecordService->create($prizeRecord);

            return $this->respondJson(['result' => 'success']);
        } else {
            return $this->respondJson(['result' => 'fail', 'code' => 1]);
        }
    }

    /**
     * 编辑活动信息
     *
     * @param Request             $request
     * @param ActivityInfoService $activityService
     * @param PrizeRecordService  $prizeRecordService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function modify(Request $request, ActivityInfoService $activityService, PrizeRecordService $prizeRecordService)
    {
        $activityInfo = $request->input('activity');
        if (is_string($activityInfo)) {
            $activityInfo = json_decode(str_replace('\'', '"', $activityInfo), true);
        }
        $conditions = ['id' => $activityInfo['id']];
        $activityInfo = $activityService->modifyActivity($activityInfo, $conditions);
        if ($activityInfo) {
            foreach ($request->input('prize') as $requestDatum) {
                $prizeRecord[] = [
                    'activity_id' => $activityInfo['id'],
                    'prize_id'    => $requestDatum['prize_id'],
                    'limit'       => $requestDatum['limit'],
                    'number'      => $requestDatum['number'],
                    'summary'     => $requestDatum['summary'],
                    'probability' => $requestDatum['probability'],
                    'operate'     => PrizeRecord::DELIVERY,
                    'created_at'  => date('Y-m-d H:i:s'),
                ];
            }
            $prizeRecordService->create($prizeRecord);

            return $this->respondJson(['prize' => $activityInfo]);
        } else {
            return $this->respondJson(['prize' => [], 'code' => 1]);
        }
    }

    /**
     * 删除活动信息
     *
     * @param Request             $request
     * @param ActivityInfoService $activityService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request, ActivityInfoService $activityService)
    {
        $result = $activityService->deleteActivity($request->request->get('activity_id'));
        if ($result) {
            return $this->respondJson(['result' => 'success']);
        } else {
            return $this->respondJson(['result' => 'fail', 'code' => 1]);
        }
    }

    /**
     * 结算活动相关信息，包括中奖信息
     *
     * @param Request             $request
     * @param ActivityInfoService $activityService
     * @param PrizeRecordService  $prizeRecordService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function settle(Request $request, ActivityInfoService $activityService, PrizeRecordService $prizeRecordService)
    {
        if ($request->request->get('activity_id')) {
            $activityInfo = $activityService->getActivity($request->request->get('activity_id'));
            if ($activityInfo['deleted_at']) {
                return $this->respondJson(['activity' => '非法操作', 'code' => 1]);
            }
            foreach ($activityInfo['activity_record'] as $activityRecord) {
                if (!isset($number[$activityRecord['prize_id']])) {
                    $number[$activityRecord['prize_id']] = 0;
                }
                if (!isset($amount[$activityRecord['prize_id']])) {
                    $amount[$activityRecord['prize_id']] = 0;
                }
                $number[$activityRecord['prize_id']] += $activityRecord['number'];
                $amount[$activityRecord['prize_id']] += $activityRecord['amount'];
            }
            foreach ($activityInfo['prize_record'] as $prizeRecord) {
                $prizeRecords[] = [
                    'prize_id'    => $prizeRecord['prize_id'],
                    'activity_id' => $request->request->get('activity_id'),
                    'number'      => $prizeRecord['number'] - @$number[$prizeRecord['prize_id']],
                    'summary'     => $prizeRecord['summary'] - @$amount[$prizeRecord['prize_id']],
                    'created_at'  => date('Y-m-d H:i:s'),
                ];
            }
            $prizeRecordService->create($prizeRecords);
            $activityService->deleteActivity(['id' => $request->request->get('activity_id')], true);

            return $this->respondJson(['result' => 'success']);
        } else {
            return $this->respondJson(['activity' => 'fail', 'code' => 1]);
        }
    }

    /**
     * 中奖信息
     *
     * @param Request             $request
     * @param ActivityInfoService $activityService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function destribute(Request $request, ActivityInfoService $activityService, ActivityRecordService $activityRecordService, StorageService $storageService, CsvReaderService $csvReaderService)
    {
        $activityId = $request->input('activity_id', null);
        $prizeId = $request->input('prize_id', null);
        $prizeInfo = $activityService->destributeActivity($activityId, $prizeId, $activityRecordService, $storageService, $csvReaderService);
        if ($prizeInfo) {
            return $this->respondJson(['result' => $prizeInfo]);
        }

        return $this->respondJson(['result' => [], 'code' => 1]);
    }

    public function getGroupActivity(Request $request, ActivityService $activityService)
    {
        $this->validate($request, [
            'interact_code' => 'required|string',
        ], [
            'interact_code.required' => '互动编码未填写',
            'interact_code.string'   => '互动编码格式错误',
        ]);
        $interactCode = $request->query->get('interact_code');
        $activities = $activityService->getActivityByGroup($interactCode);

        return $this->respondJson([
            'activities' => $activities,
        ]);
    }

    public function getGroupSlicePageActivity(Request $request, ActivityService $activityService)
    {

        $this->validate($request, [
            'interact_code' => 'required|string',
        ], [
            'interact_code.required' => '互动编码未填写',
            'interact_code.string'   => '互动编码格式错误',
        ]);
        $interactCode = $request->query->get('interact_code');
        //$hostUrl = $this->getHostUrl($request);
        $hostUrl = config('api.host');
        list($categories, $activities) = $activityService->getGroupActivityByType($interactCode, $hostUrl);

        return $this->respondJson([
            'categories' => $categories,
            'activities' => $activities,
        ]);
    }
}
